<?php
namespace App\Utils;

class GDUtil
{
    public static $LOGIN_CODE = "LOGIN-CODE";
    public static $USER_CODE = "USER-CODE";

    /**
     * 返回一个随机验证码
     * 验证码为纯数字
     * $size = 验证码字体大小(px)
     * $space = 字符间距
     * result['code']为验证码，result['img']为imagecreate创建的图像对象
     */
    public static function makeCode($num, $w = 140, $h = 44, $size = 20, $space = 0)
    {
        //创建图片
        $im = imagecreate($w, $h);
        $bg = imagecolorallocate($im, 236, 245, 250);   //背景色
        $fontColor = imageColorAllocate($im, 101, 101, 254);   //字体颜色
        $font = 'fonts/Mirvoshar.ttf';   //验证码字体
        $authcode = ""; //生成验证码
        for ($i = 0; $i < $num; $i++) {
            $randAsciiNumArray = array(rand(48, 57));
            $randAsciiNum = $randAsciiNumArray [0];
            $randStr = chr($randAsciiNum);

            //绘制验证码（）
            imagettftext($im, $size, rand(-30, 30), $space + ($i + 1) * $size, rand($size + 5, $h - 5), $fontColor, $font, $randStr);
            $authcode .= $randStr;
        }
        //干扰线
        $lineColor = imagecolorallocate($im, 101, 101, 254);
        //imageline($im, $space + $size, $h / 2, ($num + 1) * $size, $h / 2, $lineColor);
        imageline($im, $space + $size, $h / 2 + 1, ($num + 1) * $size, $h / 2 + 1, $lineColor);
//        //干扰点
//        for ($i = 0; $i < 250; $i++) {
//            imagesetpixel($im, rand(0, $w), rand(0, $h), $fontColor);
//        }
        $authcode = strtoupper($authcode);
        $result = ['code' => $authcode,
                   'img'  => $im];
        return $result;
    }

    /**
     * 刷新验证码
     */
    public static function refreshCode($name)
    {
        session([$name => rand(10000, 200000)]);
    }

    /**
     * 检查验证码(强制大写对比)
     *
     * 验证成功返回true 否则false
     */
    public static function checkCode($name, $code)
    {
        if (strtoupper($code) == session($name)) {
            return true;
        }
        return false;
    }
}